package kugou

import (
	"api-go/cache"
	"api-go/serializer"
	"api-go/util"
	"encoding/json"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

// 排行榜所需信息
type Top struct {
	Id     string `form:"id"`
	Limit  string `form:"limit"`
	Offset string `form:"offset"`
}

//获取排行榜详细信息
func (service *Top) TopInfo() *serializer.Response {

	if val := service.Id; val != "" {
		service.Id = val
	} else {
		service.Id = "8888"
	}
	if val := service.Limit; val != "" {
		service.Limit = val
	} else {
		service.Limit = "20"
	}

	if val := service.Offset; val != "" {
		service.Offset = val
	} else {
		service.Offset = "1"
	}
	url := "http://mobilecdnbj.kugou.com/api/v3/rank/song?version=9108&ranktype=2&plat=0&pagesize=" + service.Limit + "&area_code=1&page=" + service.Offset + "&rankid=" + service.Id + "&with_res_tag=1"

	res, err := util.KugouGetS(url)
	if err != nil {
		return err
	}
	return serializer.OkResponse(res)
}

//获取排行榜分类
func (service *Top) TopCat() *serializer.Response {
	//定义redis key和判断redis是否有该值
	redisKey := "kugou-top-cat"
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		url := "http://mobilecdnbj.kugou.com/api/v3/rank/list?version=9108&plat=0&showtype=2&parentid=0&apiver=6&area_code=1&withsong=1"

		res, err := util.Get(url)
		if err != nil {
			return err
		}

		//将结果转为Json数据
		b, e := json.Marshal(res)
		if e != nil {
			fmt.Println(err)
		}
		//转为string存入redis
		e = cache.RedisClient.Set(ctx, redisKey, string(b), 24*time.Hour).Err()
		if e != nil {
			fmt.Println("err1", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}

		return serializer.OkResponse(res)
	} else if err != nil {
		fmt.Println("err2", err)
		return serializer.ErrorResponse(serializer.RedisError)
	} else {
		//将从redis获取的结果（string类型）转为map[string]inerface{}
		bodyMapData := map[string]interface{}{}
		err = json.Unmarshal([]byte(redisResult), &bodyMapData)
		if err != nil {
			fmt.Println("err3", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}
		return serializer.OkResponse(bodyMapData)
	}
}
